﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Service;
using MetaQuotes.MT5WebAPI.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    public class InternalTransferController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        private readonly SmtpSettings _emailSender;

        public InternalTransferController(mtContext context, IWebHostEnvironment hostingEnv, SmtpSettings emailSender) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
            _emailSender = emailSender;
        }
        #region 列表       
        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="account">姓名/账户ID</param>
        /// <param name="currentReviewer">当前审核人</param>
        /// <param name="createDate">创建时间</param>
        /// <param name="type">信息类型</param>
        /// <param name="state">状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string account, string currentReviewer, string orderNo, string createDate, string field, string order, int type = -1, int state = -1)
        {

            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmInternaltransfers
                           join c in _context.CrmUsers on y.CrmId equals c.Id
                           join d in _context.Mt5Users on c.Id equals d.CrmId
                           select new
                           {
                               index = y.Id,
                               orderNumber = y.Id,
                               id = y.CrmId,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               paymentAmount = y.FromAmount == 0 ? "0.00" : ((decimal)y.FromAmount).ToString("#,##0.00"),
                               state = y.State,
                               createDate = y.CreateDate,
                               currentReviewer = y.Reviewer,
                               endTime = y.OverDate,
                               tradingAccount = d.Login
                           };
                //姓/名/账户ID
                if (!string.IsNullOrEmpty(account))
                {
                    long loginNo = 0;
                    try
                    {
                        loginNo = Convert.ToInt64(account);
                    }
                    catch
                    {
                        loginNo = 0;
                    }
                    if (loginNo == 0)
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account));
                    }
                    else
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account) || k.tradingAccount == loginNo);
                    }
                }
                //订单号
                if (!string.IsNullOrEmpty(orderNo))
                {
                    data = data.Where(k => k.orderNumber == orderNo);
                }
                if (!string.IsNullOrEmpty(currentReviewer))
                {
                    data = data.Where(k => k.currentReviewer.Contains(currentReviewer));
                }
                if (!string.IsNullOrEmpty(createDate) && createDate.Contains(" - "))
                {
                    string[] createDates = createDate.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(createDates[0]);
                    DateTime endTime = Convert.ToDateTime(createDates[1]);
                    data = data.Where(k => k.createDate > startTime && k.createDate < endTime);
                }

                if (state > -1)
                {
                    data = data.Where(k => k.state == state);
                }

                if (!string.IsNullOrEmpty(field))
                {
                    if (string.IsNullOrEmpty(order))
                    {
                        data = data.OrderBy(k => field).ThenBy(k => k.orderNumber);
                    }
                    else if (order == "asc")
                    {
                        data = data.OrderBy(k => field);
                    }
                    else
                    {
                        data = data.OrderByDescending(k => field);
                    }

                }
                else
                {
                    data = data.OrderBy(k => k.state).ThenByDescending(k => k.createDate);
                }
                res.Count = data.Count();

                res.Data = await data.Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }

        }
        #endregion

        #region 内部转账信息
        public async Task<IActionResult> InternalTransferDetail(string id)
        {

            #region 获取内部转账信息        
            CrmInternaltransfer crmInternaltransfer = await _context.CrmInternaltransfers.FindAsync(id);
            if (crmInternaltransfer == null)
            {
                return NotFound();
            }
            ViewBag.FromAmount = crmInternaltransfer.FromAmount == 0 ? "0.00" : ((decimal)crmInternaltransfer.FromAmount).ToString("#,##0.00");
            ViewBag.ToAmount = crmInternaltransfer.ToAmount == 0 ? "0.00" : ((decimal)crmInternaltransfer.ToAmount).ToString("#,##0.00");
            ViewBag.Fees = crmInternaltransfer.Fees == 0 ? "0.00" : ((decimal)crmInternaltransfer.Fees).ToString("#,##0.00");
            #endregion

            #region 获取用户信息
            CrmUser crmUser = await _context.CrmUsers.FindAsync(crmInternaltransfer.CrmId);
            if (crmUser == null)
            {
                return NotFound();
            }
            ViewBag.crmUsers = crmUser;
            #endregion

            #region 审核记录

            var data = from y in _context.CrmAuditLogs
                       join c in _context.TbUsers on y.ReviewerId equals c.Id into cc
                       from ccdata in cc.DefaultIfEmpty()
                       join d in _context.CrmUsers on y.CrmId equals d.Id
                       select new CrmAuditLog
                       {
                           Id = y.Id,
                           OrderId = y.OrderId,
                           CrmId = y.CrmId,
                           Type = y.Type,
                           Cont = y.Cont,
                           Remark = y.Remark,
                           Reviewer = y.ReviewerId != null ? ccdata.UserName : d.Name,
                           CreateDate = y.CreateDate,
                           ReviewerId = y.ReviewerId

                       };
            var crmAuditLogs = data.Where(k => k.OrderId == crmInternaltransfer.Id.ToString() && k.Type == 6).OrderBy(p => p.Id).ToList();
            ViewBag.crmAuditLogsList = crmAuditLogs;
            #endregion

            #region 登录用户名
            ViewBag.LoginName = User.UserName;
            #endregion

            return View(crmInternaltransfer);
        }
        #endregion

        #region 保存审核信息
        [HttpPost]
        public async Task<JsonResult> Edit(string Id, int State, string Remarks, string Reviewer, double Toamount)
        {
            Result res = new Result();
            ulong ticker = 0;
            try
            {
                CrmInternaltransfer crmInternaltransfer = await _context.CrmInternaltransfers.FindAsync(Id);
                MT5CommonHelper mT5CommonHelper = new MT5CommonHelper();
                if (crmInternaltransfer == null)
                {
                    res.Code = 1;
                    res.Msg = "gettingInformationFailure";
                    return new JsonResult(res);
                }

                if (crmInternaltransfer.FromAmount <= 0)
                {
                    res.Code = 1;
                    res.Msg = "depositRestrictions";
                    return new JsonResult(res);
                }

                #region 判断是否有服务器可用 
                Mt5Server mt5Server = _context.Mt5Servers.Where(k => k.State == 1 && k.Type == 1).OrderByDescending(k => k.Default).ThenBy(k => k.Sort).FirstOrDefault();
                if (mt5Server == null)
                {
                    res.Code = 1;
                    res.Msg = "warningMt5";
                    return new JsonResult(res);
                }
                #endregion


                #region 判断状态是否改变
                if (crmInternaltransfer.State != 0)
                {
                    res.Code = 1;
                    res.Msg = "warningUser";
                    return new JsonResult(res);
                }
                #endregion

                #region 判断是否入金
                decimal fees = crmInternaltransfer.FromAmount - Convert.ToDecimal(Toamount);
                if (State == 2)
                {

                    bool MTRetCode = mT5CommonHelper.TradeBalance(_context, Convert.ToUInt64(crmInternaltransfer.Login), MTDeal.EnDealAction.DEAL_BALANCE, "internalTransferIn", Convert.ToDouble(crmInternaltransfer.FromAmount), crmInternaltransfer.Remark, Toamount, fees, User.LoginName, out ticker);
                    if (!MTRetCode)
                    {
                        res.Code = 1;
                        res.Msg = "depositFailed";
                        return new JsonResult(res);
                    }
                    else
                    {
                        #region 修改MT5用户表数据
                        Mt5User mt5User = _context.Mt5Users.Where(k => k.Login == crmInternaltransfer.Login).FirstOrDefault();
                        if (mt5User != null)
                        {
                            MTUser tmu = mT5CommonHelper.QueryUsers(Convert.ToUInt64(crmInternaltransfer.Login));
                            mt5User.Balance = Convert.ToDecimal(tmu.Balance);
                            mt5User.UpdateDate = DateTime.Now;
                        }
                        #endregion
                    }
                }
                else
                {
                    #region 审核拒绝 
                    //CMR退钱
                    CrmWallet crmWallet = await _context.CrmWallets.FindAsync(crmInternaltransfer.Walletid);
                    decimal Balance = crmWallet.Balance;
                    decimal FromAmount = crmWallet.Balance + crmInternaltransfer.FromAmount;
                    if (crmWallet == null)
                    {
                        res.Code = 1;
                        res.Msg = "gettingInformationFailure";
                        return new JsonResult(res);
                    }
                    crmWallet.Balance = FromAmount;
                    //新增钱包流水
                    CrmWalletTransaction crmWalletTransaction = new CrmWalletTransaction();
                    crmWalletTransaction.Id = CommonHelper.GetOrderNo();
                    crmWalletTransaction.WalletId = crmInternaltransfer.Walletid;
                    crmWalletTransaction.Type = "cashDeposit";
                    crmWalletTransaction.Mode = "internalTransferRefund";
                    crmWalletTransaction.BeforeAmount = Balance;
                    crmWalletTransaction.Amount = crmInternaltransfer.FromAmount;
                    crmWalletTransaction.AfterAmount = FromAmount;
                    crmWalletTransaction.CreateDate = DateTime.Now;
                    crmWalletTransaction.OrderId = ticker.ToString();
                    crmWalletTransaction.From = crmInternaltransfer.CrmId.ToString();
                    crmWalletTransaction.To = crmInternaltransfer.Login.ToString();
                    _context.Add(crmWalletTransaction);
                    #endregion
                }
                #endregion

                #region 修改内部转账表数据
                crmInternaltransfer.State = State;
                crmInternaltransfer.Reviewer = User.UserName;
                crmInternaltransfer.OverDate = DateTimeUtil.Now;
                crmInternaltransfer.Mt5Order = ticker.ToString();
                crmInternaltransfer.ToAmount = Convert.ToDecimal(Toamount);
                crmInternaltransfer.Fees = fees;               
                #endregion

                #region 新增审核记录
                CrmAuditLog crmAuditLog = new CrmAuditLog();
                crmAuditLog.OrderId = crmInternaltransfer.Id.ToString();
                crmAuditLog.CrmId = crmInternaltransfer.CrmId;
                crmAuditLog.Type = 6;
                if (State == 2)
                    crmAuditLog.Cont = "审核通过";
                else
                    crmAuditLog.Cont = "审核拒绝";
                crmAuditLog.Reviewer = User.UserName;
                crmAuditLog.Remark = Remarks;
                crmAuditLog.ReviewerId = User.Id;
                crmAuditLog.CreateDate = DateTimeUtil.Now;
                _context.Add(crmAuditLog);
                #endregion


                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);

            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);

            }

        }
        #endregion
    }
}
